import config from './config'
import store from '../store/index'
import pinyin from "wl-pinyin"
import QQMapWX from '@/utils/qqmap-wx-jssdk.min.js'
let func = {

	navigateTo(e) {
		console.log(e)
		const url = e.currentTarget.dataset.url
		const passlogin = e.currentTarget.dataset.passlogin == 1

		if (!passlogin) {
			if (!store.state.user.isLogin && url.indexOf('login') == -1 && url.indexOf('common') == -1) {
				uni.reLaunch({
					url: '/pages/login/index?showLogin=1'
				})
				return
			}
		}
		uni.navigateTo({
			url: url
		})
	},
	tips(title) {
		uni.showToast({
			title: title,
			icon: "none",
			mask: true,
			duration: 3000,
		})
	},

	toUrl(url, params = {}) {
		const p = []
		for (let i in params) {
			p.push(i + '=' + params[i])
		}
		const paramsStr = p.length > 0 ? '?' + p.join("&") : ''
		uni.navigateTo({
			url: url + paramsStr
		})
	},
	atUrl(url) {

		uni.reLaunch({
			url: url
		})
	},

	toBack() {
		if (getCurrentPages().length <= 1) {
			uni.reLaunch({
				url: '/pages/index/index?active=0'
			});
		} else {
			uni.navigateBack({
				delta: 1
			});
		}
	},
	redirectTo(e) {
		uni.navigateTo({
			url: e.currentTarget.dataset.url
		})
	},
	makePhoneCall(tel = null) {
		const phone = uni.getStorageSync('phone') || "";
		const res = tel ? tel : phone
		uni.makePhoneCall({
			phoneNumber: res
		});
	},
	webUrl(url = '') {
		return config.website + url
	},
	webAppUrl(url = '') {
		return config.website + '/statics/images/app/' + url
	},
	ossUrl(url = '') {
		return config.ossUrl + url
	},
	website(url = '') {
		return 'http://ylhl.oshainiu.cn' + url
	},
	checkPhone(phone) {
		if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(phone))) {
			return false;
		} else {
			return true
		}
	},
	checkTelephone(phone) {
		return /^((\+86)|(86))?(1)\d{10}$/.test(phone) || /^0[0-9-]{10,13}$/.test(phone);
	},
	getThumb(img) {
		let arr = []
		if (img) {
			arr = img.split(',')

		}
		if (arr.length > 0) {
			return arr[0]
		} else {
			return ""
		}
	},
	getSystemInfo() {
		return new Promise((resolve, reject) => {
			uni.getSystemInfo({
				success: function(res) {
					resolve(res);
					// console.log(res.model);
					// console.log(res.pixelRatio);
					// console.log(res.windowWidth);
					// console.log(res.windowHeight);
					// console.log(res.language);
					// console.log(res.version);
					// console.log(res.platform);
				},
				fail(err) {
					resolve(err);
				}
			});

		});
	},
	getWords(e, len = 32) { // js字数与数据库字符数不一样
		let b = 0 // 输入的字符数
		let newArr = []
		let newStr = ""
		for (var i = 0, length = e.length; i < length; i++) {
			var c = e.charAt(i);
			if (/^[\u0000-\u00ff]$/.test(c)) {
				b++;
			} else {
				b += 2;
			}

			if (b <= len) {

			} else {
				newArr.push(newStr)
				b = 0
				newStr = ""
			}
			newStr = newStr + e.charAt(i)

		}
		newArr.push(newStr)
		return newArr
	},
	curRoute() {
		let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
		let curRoute = routes[routes.length - 1].route //获取当前页面路由
		return curRoute
	},
	consoleLog(...arg) {
		if (process.env.NODE_ENV == 'development') {
			console.log(...arg)
		}
	},
	wordsList(list, key = 'nickName') {
		var res = {}
		for (let i = 0; i < 26; i++) {
			var char = String.fromCharCode(65 + Number(i));
			res[char] = []
		}
		res['#'] = []
		// console.log(res)
		for (let vo of list) {
			const py = vo[key] ? pinyin.getFirstLetter(vo[key]).split("") : [];
			if (py.length > 0) {
				if (res[py[0].toUpperCase()]) {
					res[py[0].toUpperCase()].push(vo)
				} else {
					res["#"].push(vo)
				}
			}
		}
		var returnData = {
			indexList: [],
			itemArr: [],
		}
		for (let i in res) {
			if (res[i].length > 0) {
				returnData.indexList.push(i.toUpperCase())
				returnData.itemArr.push(res[i])
			}
		}

		return returnData
	},
	formatDateWithZero(date) {
		var arr = date.split('-')
		// 补零处理
		if (arr[1]) {
			arr[1] = arr[1].length == 1 ? '0' + arr[1] : arr[1];
		}
		if (arr[2]) {
			arr[2] = arr[2].length == 1 ? '0' + arr[2] : arr[2];
		}
		// 返回格式化后的日期字符串
		return arr.join('-');
	},
	previewImage(current, urls) {
		uni.previewImage({
			urls: urls,
			current: current,
		})
	},
	downloadFile(attorneyPath, fileExtName) {
		const type = fileExtName.toLowerCase()
		if (['jpg', 'jpeg', 'png', 'gif'].includes(fileExtName)) {
			uni.previewImage({
				urls: [attorneyPath],
				current: attorneyPath,
			})
			return
		}
		let that = this;
		const randfile = new Date().getTime() + '.' + fileExtName;
		const newPath = `${wx.env.USER_DATA_PATH}/${randfile}`;
		func.deletContract();
		uni.showLoading({
			title: "请稍等"
		})
		wx.downloadFile({
			url: attorneyPath,
			success: function(res) {
				// wx.shareFileMessage({
				// 	filePath: res.tempFilePath,
				// 	success() {
				// 		uni.hideLoading();
				// 		console.log('转发文档成功')
				// 	},
				// 	fail: function(error) {
				// 		uni.hideLoading();
				// 		console.log(error)
				// 	},
				// })
				if (['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf'].includes(fileExtName)) {
					wx.openDocument({
						filePath: res.tempFilePath,
						fileType: fileExtName,
						success: function(rest) {
							uni.hideLoading();
							console.log('打开文件成功')
							console.log(rest);
						},
						fail: function(error) {
							uni.hideLoading();
							console.log(error)
							wx.showToast({
								icon: 'none',
								title: '打开文件失败'
							});
						},
					})
				} else {
					wx.shareFileMessage({
						filePath: res.tempFilePath,
						success() {
							uni.hideLoading();
							console.log('转发文档成功')
						},
						fail: function(error) {
							uni.hideLoading();
							console.log(error)
						},
					})
				}

			},
			fail: (err) => {
				uni.hideLoading();
				console.log(err)
			}
		})

	},
	deletContract() {
		try {
			let file = uni.getFileSystemManager();
			file.readdir({
				dirPath: `${wx.env.USER_DATA_PATH}`,
				success: res => {
					if (res.files.length > 2) {
						file.unlink({
							filePath: `${wx.env.USER_DATA_PATH}/${res.files[0]}`,
							complete: res => {

							}
						})
					}
				}
			})
		} catch (error) {

		}
	},
	openLocation(latitude, longitude, name) {
		wx.openLocation({
			latitude: +latitude,
			longitude: +longitude,
			name: name,
			success: function() {
				console.log('success');
			},
			fail: function(err) {
				console.log(err);
			},
		});
	},
	getMapAddress() {
		uni.authorize({
			scope: 'scope.userLocation',
			success() { //1.1 允许授权
				func.getLocation();
			},
			fail() { //1.2 拒绝授权
				uni.showModal({
					content: '检测到您没打开获取信息功能权限，是否去设置打开？',
					confirmText: "确认",
					cancelText: '取消',
					success: (res) => {
						if (res.confirm) {
							uni.openSetting({
								success: (res) => {
									func.getLocation();
								}
							})
						} else {
							console.log('取消');
							return false;
						}
					}
				})
				return false;
			}
		})
	},
	getLocation() {
		var address = {
			lbsName: "",
			lbsAddress: "",
			longitude: "",
			latitude: "",
		}
		const tMap = new QQMapWX({
			key: '' //开发者密钥
		});
		// wx.getFuzzyLocation({
		// 	type: 'wgs84',
		// 	success: (res) => {
		// 		console.log("获取经纬度成功",res);

		// 	},
		// })
		//使用 uni.getLocation获取用户所在经纬度
		uni.getLocation({
			type: 'wgs84',
			geocode: true,
			success: (res) => {
				console.log("获取经纬度成功");
				// const re = _this.$mapChange.wgs84Togcj02(res.longitude, res.latitude)
				address.longitude = res.longitude
				address.latitude = res.latitude
			},
			fail: () => {
				console.log("获取经纬度失败");
			},
			complete: () => {
				// 使用腾讯sdk的reverseGeocoder方法 解析经纬度
				tMap.reverseGeocoder({
					location: {
						latitude: address.latitude,
						longitude: address.longitude
					},
					success: function(res) {
						console.log("解析地址成功", res);
						console.log("当前地址：", res.result.address);
						address.lbsAddress = res.result.formatted_addresses && res.result
							.formatted_addresses.standard_address || res.result.address
						address.lbsName = res.result.formatted_addresses && res.result
							.formatted_addresses.recommend || res.result.address
						store.commit('setAddress', address)
					},
					fail: function(res) {
						// uni.showToast({
						// 	title: res.message,
						// 	duration: 2000,
						// 	icon: "none"
						// })
						console.log(res);
					},
					complete: function(res) { //无论成功失败都会执行
						console.log('获取定位信息')
						return
						// uni.openLocation({
						// 	latitude: address.latitude,
						// 	longitude: address.longitude,
						// 	success: function() {
						// 		console.log('success');
						// 	}
						// });
					}
				})

			}
		})
	},
	shareApp() {
		var pages = getCurrentPages() // 获取栈实例
		let currentRoute = pages[pages.length - 1].route; // 获取当前页面路由
		console.log("路由当前页面路径" + currentRoute)
		let currentPage = pages[pages.length - 1]['$page']['fullPath'] //当前页面路径(带参数)

		return {
			title: '利溪设备维护',
			path: currentPage, // 路径，传递参数到指定页面。
			success: (res) => {
				uni.showToast({
					title: '分享成功',
					icon: "none",
					duration: 2000
				});
			}
		}
	}
}

export default func